<template>
    <el-dialog :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="60%" append-to-body :fullscreen="fullscreen">
        <el-form :model="dialogForm" size="small" :disabled="type==3" label-suffix=":" ref="detailForm" :rules="rules" label-width="100px">
            <el-row>
                <el-col :span="12">
                    <!--              物料名称：-->
                    <el-form-item :label="$t('basicData.materialName')" prop="materialName">
                        <el-input :disabled="type != 1" v-model="dialogForm.materialName" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <!--              物料编号：-->
                    <el-form-item :label="$t('basicData.materialNo')" prop="materialCode">
                        <el-input :disabled="type != 1" v-model="dialogForm.materialCode" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <!--              厂区：-->
                    <el-form-item :label="$t('basicData.factoryName')" prop="plantName">
                        <el-select class="line_select" style="width:100%" v-model="dialogForm.plantName" :placeholder="$t('formErrMsg.selectFactory')" filterable>
                            <el-option v-for="dict in factoryOptions" :key="dict.plantId" @click.native="changeFactory(dict)" :label="dict.plantName" :value="dict.plantName" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <!--              检验标准时长：-->
                    <el-form-item :label="$t('basicData.StandardInspectionDuration')" prop="inspectionDuration">
                        <el-input placeholder="请输入内容" @input="(val)=>{dialogForm.inspectionDuration = val.replace(/[^\d]/g, '')}" v-model="dialogForm.inspectionDuration">
                            <template slot="append">小时</template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <!--              类型：-->
                    <el-form-item ref="materialType" label="材料类型" prop="materialKind">
                        <el-select v-model="dialogForm.materialKind" style="width:100%"   filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')+$t('basicData.materialType')">
                            <el-option v-for="(item,index) in materialOptions" :key="index" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
               
                <el-col :span="12">
                    <!--              物料等级-->
                    <el-form-item ref="materialType" label="物料等级" prop="materialLevel">
                        <el-select v-model="dialogForm.materialLevel" style="width:100%"   filterable size="small" reserve-keyword :placeholder="$t('public.selectPl')">
                            <el-option v-for="(item,index) in dict.type.QC_MASTERDATA__MATERIAL_LEVEL" :key="index" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
             

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import {listAllMaterialMessageMessage} from '@/api/basic/gaugeMessage'
import {addMaterialMessage, updateMaterialMessage,} from '@/api/basic/materialMessage'
import {listALLFactory} from '@/api/basic/factory'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'
import {getMasterialMaxMinData} from '@/api/basic/materialtype'

export default {
    name: 'mtool-detial',
    components: { EnjoySelectUser, EnjoySelectDeptTree, FileUploadInput },
    dicts: [  
        'QC_MASTERDATA__MATERIAL_LEVEL'
    ],
    props: {
        value: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    watch: {
        value(val) {
            this.dialogForm = { ...val }
        },
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title =
                    this.$t('public.add') +
                    ' ' +
                    this.$t('basicData.materialInfo')
            }
            if (type == 2) {
                title =
                    this.$t('public.edit') +
                    ' ' +
                    this.$t('basicData.materialInfo')
            }
            // if(type == 3){
            //   title = this.$t('mtool.viewHeader')
            // }
            return title
        },
    },
    data() {
        return {
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: [],
            dialogForm: {},
            // 表单校验
            rules: {
                materialName: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialNameCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                materialCode: [
                    {
                        required: true,
                        message: '物料编号不能为空',
                        trigger: 'blur',
                    },
                ],
                plantName: [
                    {
                        required: true,
                        message: this.$t('formValidation.factoryAreaCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                inspectionDuration: [
                    {
                        required: true,
                        message: '检验标准时长不能为空',
                        trigger: 'blur',
                    },
                ],
                materialMax: [
                    {
                        required: true,
                        message: '物料大类不能为空',
                        trigger: 'change',
                    },
                ],
                materialMiddle: [
                    {
                        required: true,
                        message: this.$t('formValidation.theClassInTheMaterialCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                materialKind: [
                    {
                        required: true,
                        message: '材料类型不能为空',
                        trigger: 'change',
                    },
                ],
                materialLevel: [
                    {
                        required: true,
                        message: '物料等级不能为空',
                        trigger: 'change',
                    },
                ],
                // messagePpm: [
                //     {
                //         required: true,
                //         message: 'PPM不能为空',
                //         trigger: 'blur',
                //     },
                // ],
                // percentPass: [
                //     {
                //         required: true,
                //         message: '目标合格率不能为空',
                //         trigger: 'blur',
                //     },
                // ],
            },
            materialMaxOptions: [],
            materialOptions: [
                {value:"1",label:"主材"},
                {value:"2",label:"辅材"}
            ],
            materialMiddleOptions: [],
        }
    },
    mounted() {
        // this.getMaterialType({}, 'materialMax')
        // this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
        // this.getMaterialType({ materialMiddle: 'all' }, 'typeName')
        this.factoryRemoteMethod()
        this.dialogForm = { ...this.value }
    },
    methods: {
        changeFactory(dict) {
            
            this.dialogForm.plantName = dict.plantName
            this.dialogForm.plantCode = dict.plantCode
        },
        loadNumber(event) {
            let elValue = event
            let reg = /^((?!0)\d{1,2}|100)$/
            if (!elValue.match(reg)) {
                this.$set(this.dialogForm, 'percentPass', '')
                return false
            } else {
                return true
            }
        },
        getMaterialType(params, name) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[name])
                if (name === 'materialMax') {
                    this.materialMaxOptions = array
                } else if (name === 'materialMiddle') {
                    this.materialMiddleOptions = array
                } else {
                    this.materialOptions = array
                }
            })
        },
        /** 发起提交 */
        submitForm: function () {
            this.loading = true
            this.$refs.detailForm.validate((valid) => {
                let action =
                    this.type == 1 ? addMaterialMessage : updateMaterialMessage
                if (valid) {
                    action(this.dialogForm).then((res) => {
                        this.loading = false
                        if (res.code == 200) {
                            this.$emit('refresh')
                            this.$modal.msgSuccess('操作成功!')
                            this.$emit('update:visible', false)
                        } else {
                            this.$modal.msgError(res.msg)
                            this.loading = false
                        }
                    })
                } else {
                    this.loading = false
                }
            })
        },
        insectionChangeValue() {},
        handleClose(done) {
            this.dialogForm = {}
            this.$refs['detailForm'].clearValidate()
            this.$emit('update:visible', false)
        },
        //设备模糊查询
        deviceRemoteMethod(val, cb) {
            console.log(val)
            listAllMaterialMessageMessage({ deviceName: val }).then((res) => {
                this.deviceOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleDeviceSelect(e) {
            this.dialogForm.deviceName = e.deviceName
            this.dialogForm.gaugeType = e.gaugeType
            this.$refs.deviceName.$emit('el.form.blur')
        },
        handleDeviceBlur(e) {
            const { deviceOptions, dialogForm } = this
            if (!deviceOptions.includes(dialogForm.deviceName)) {
                this.dialogForm.deviceName = ''
            }
        },
        //工厂模糊查询
        factoryRemoteMethod(val, cb) {
            listALLFactory({ factoryName: '' }).then((res) => {
                this.factoryOptions = res.data
            })
        },
        handleMaterialMaxChange(e) {
            this.getMaterialType({ materialMax: e || 'all' }, 'materialMiddle')
            if (this.dialogForm.materialMiddle) {
                this.$set(this.dialogForm, 'materialMiddle', '')
            }
            if (this.dialogForm.materialType) {
                this.$set(this.dialogForm, 'materialType', '')
            }
        },
        handleMaterialMiddleChange(e) {
            this.getMaterialType({ materialMiddle: e || 'all' }, 'typeName')
            if (this.dialogForm.materialType) {
                this.$set(this.dialogForm, 'materialType', '')
            }
        },
        handleFactorySelect(e) {
            this.dialogForm.plantName = e.plantName
            this.$refs.plantName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.plantName)) {
                this.dialogForm.plantName = ''
            }
        },
        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        handleRespName(e) {
            this.dialogForm.respName = e.name
        },
        handleEmployName(e) {
            this.dialogForm.employName = e.name
        },
        handleRespDept(e) {
            this.dialogForm.respDept = e.name
        },
    },
}
</script>

<style scoped>
</style>
